// opcua-client.js
import {
  OPCUAClient,
  AttributeIds,
  TimestampsToReturn,
  ClientSubscription,
  ClientMonitoredItem,
  ClientSession,
  DataValue
} from 'node-opcua'

async function connectToServer(
  endpointUrl: string,
  nodeId: string,
  onDataChange: (arg0: DataValue) => void
): Promise<{
  client: OPCUAClient
  session: ClientSession
  subscription: ClientSubscription
  monitoredItem: ClientMonitoredItem
}> {
  const client = OPCUAClient.create({ endpointMustExist: false })
  await client.connect(endpointUrl)

  const session = await client.createSession()

  const subscription = ClientSubscription.create(session, {
    requestedPublishingInterval: 1000,
    requestedMaxKeepAliveCount: 10,
    requestedLifetimeCount: 30,
    maxNotificationsPerPublish: 10,
    publishingEnabled: true,
    priority: 10
  })

  const monitoredItem = ClientMonitoredItem.create(
    subscription,
    {
      nodeId: nodeId, // 例如 "ns=1;s=Temperature"
      attributeId: AttributeIds.Value
    },
    {
      samplingInterval: 1000,
      discardOldest: true,
      queueSize: 10
    },
    TimestampsToReturn.Both
  )

  monitoredItem.on('changed', (dataValue) => {
    onDataChange(dataValue.value.value)
  })

  monitoredItem.on('error', (error)=>{
    console.log(error)
  })

  return {
    client,
    session,
    subscription,
    monitoredItem
  }
}

export { connectToServer }
